// 定义
var background = $('.bg');
var bird = $('.bird');
var sky = {
    x: 0,
};

var birdicon = {
    speedX: 5,
    speedY: 0,
    x: bird.css('left'),
    y: bird.css('top'),
}

// 经过的管道数
var pipeNum = 0;
var flag = false;

// 管道
var pipe = {
    speedL: 6,
};

// 点击设置的各个变量
$('.set').click(function () {
    $('.setConBox').css('display', 'block');
})

$('.close').click(function (event) {
    console.log('click!!!');
    // 发生冲突！！！
    event.stopPropagation();
    $('.setConBox').css('display')
    $('.setConBox').css('display', 'none')
})

/* 
鸟儿体重：
速度：
鸟儿弹跳能力：
管道水平间距：
管道垂直间距 
*/
var weight = $('.weight input');
var speed = $('.speed input');
var jump = $('.jump input');
var horz = $('.horz input');
var vert = $('.vert input');
var value = 0;
var valueMap = new Map([
    ['weight', '5'],
    ['speed', '7'],
    ['jump', '4'],
    ['horz', '6'],
    ['vert', '6'],
]);
/* 1: -> 80毫秒
   2: -> 50毫秒
   3: -> 40毫秒
   4: -> 30毫秒（初始）
   5: -> 20毫秒
   6: -> 10毫秒
   7: -> 5毫秒 */
var speedMap = new Map([
    ['1', '80'],
    ['2', '50'],
    ['3', '40'],
    ['4', '30'],
    ['5', '20'],
    ['6', '10'],
    ['7', '5'],
])

// 初始管道数量
var initialPN = 0;
// 初始水平间距
var pipehorz = 0;

/* 自适应开始 */
// 初始宽度
console.log('$(window).width():', $(window).width());
background.width($(window).width());

// 鸟和管的初始位置
bird.css('left', background.width() / 6);
var initialPipeL = 0;

if (background.width() < 500) {
    initialPipeL = background.width() * .8;
    bird.css('top', background.height() / 2);
} else {
    initialPipeL = background.width() * .4;
    bird.css('top', background.height() / 2.5);
}

// 创建初始管
/* 管道水平间距！！！！！！ */
function initialPipe() {
    initialPN = background.width() / (52 * horz.val());
    console.log('初始管道数量：' + (parseInt(initialPN) + 2));
    pipehorz = 50 * parseInt(horz.val());
    console.log('初始水平间距：' + pipehorz);
    for (var i = 0; i < parseInt(initialPN) + 2; i++) {
        console.log(i);
        createPipe(initialPipeL + i * pipehorz, i);
    }
}

initialPipe();

window.onresize = resizefunc;

// 窗口变化时重新创建管道，控制管道大小和鸟的位置
function resizefunc() {
    background.width($(window).width());
    bird.css('left', background.width() / 6);
    if (background.width() < 500) {
        initialPipeL = background.width() * .8;
        bird.css('top', background.height() / 2);
    } else {
        initialPipeL = background.width() * .4;
        bird.css('top', background.height() / 2.5);
    }
    initialPipe();
}
/* 自适应结束 */


/* 按钮的控制开始 */
function disabled(input) {
    if (input.val() <= 1) {
        input.siblings('.more').attr('disabled', false);
        input.siblings('.less').attr('disabled', true);
    } else {
        input.siblings('.less').attr('disabled', false);
    }
    if (valueMap.has(input.parent().attr('class'))) {
        if (input.val() >= valueMap.get(input.parent().attr('class'))) {
            input.siblings('.more').attr('disabled', true);
        } else {
            input.siblings('.more').attr('disabled', false);
        }
    }
}

function moreLess() {
    $('.more').click(function () {
        value = $(this).siblings("input").val();
        $(this).siblings("input").val(++value);
        disabled($(this).siblings("input"));
    })
    $('.less').click(function () {
        value = $(this).siblings("input").val();
        $(this).siblings("input").val(--value);
        disabled($(this).siblings("input"));
    })
}
moreLess();
/* 按钮的控制结束 */

// 重置小鸟位置与速度
function resetBird() {
    if (background.width() < 760) {
        bird.css('top', background.height() / 2);
    } else {
        bird.css('top', background.height() / 2.5);
    }
    birdicon = {
        speedX: 5,
        speedY: 0,
        x: bird.css('left'),
        y: bird.css('top'),
    }
}

// 重置管的位置
function resetPipe() {
    $('.pipeBox').remove();
    initialPipe();
}

$('.start').click(function () {
    resetBird();
    go();
    $('.start').hide();
    $('.set').hide();
});

$('.restart').click(function () {
    pipeNum = 0;
    resetBird();
    resetPipe();
    go();
    $('.restart').hide();
    $('.set').hide();
});

// 主要执行函数
function go() {
    // 先声明变量，以防止多次执行函数多次生成变量，减少空间复杂度
    var initialL = 0;
    var thenL = 0;
    var thisTpipe = 0;
    var thisBpipe = 0;
    var pipeL = 0;
    var birdL = 0;
    var birdW = 0;
    var birdH = 0;
    var birdY = 0;
    var birdHeight = 0;
    var gofunc = setInterval(function () {
        // 背景
        sky.x -= 5;
        background.css('background-positionX', sky.x + 'px');

        // 鸟
        if (birdicon.speedY < 3) {
            birdicon.speedY += .4;
            console.log('速度：' + birdicon.speedY);
        } else {
            /* 鸟的体重！！！！！33333333 */
            console.log('weight.val(): ' + weight.val());
            birdicon.speedY = parseInt(weight.val());
        }
        birdicon.y = parseInt(birdicon.y) + birdicon.speedY + 'px';
        console.log('birdicon.y: ' + birdicon.y);
        bird.css('top', birdicon.y);

        // 管道
        $('.tpipe').each(pipego);
        $('.bpipe').each(pipego);

        // 管道的移动以及重新设置管道位置
        function pipego() {
            initialL = $(this).css('left');
            thenL = parseInt(initialL) - pipe.speedL;
            $(this).css('left', thenL + 'px');
            if (parseInt($(this).css('left')) < -52) {
                // $(this).css('left', parseInt(initialPipeL) + 648 + 'px');
                $(this).css('left', ((pipehorz) * (parseInt(initialPN) + 1)) + (parseInt(pipehorz) - 52) + 'px');
                $(this).css('height', getRandom());
            }
        }

        // 碰撞
        thisTpipe = $('.tpipe').eq(pipeNum % (parseInt(initialPN) + 2));
        thisBpipe = $('.bpipe').eq(pipeNum % (parseInt(initialPN) + 2));
        console.log('第几个管子:' + pipeNum % (parseInt(initialPN) + 2));
        pipeL = parseInt(thisTpipe.css('left'));
        birdL = parseInt(bird.css('left'));
        birdW = parseInt(bird.width());
        birdH = parseInt(bird.height());
        birdY = parseInt(birdicon.y);
        /* console.log('pipeNum: ' + pipeNum);
        console.log('pipeL: ' + pipeL);
        console.log('birdL: ' + birdL);
        console.log('birdY: ' + birdY); */

        // 当管道即将进入可能与小鸟发生碰撞区域
        if (birdL <= (pipeL + 52) && (birdL + birdW) >= pipeL) {
            console.log('快撞到啦！！！！');
            /* console.log('birdL: ' + birdL);
            console.log('birdH: ' + birdH);
            console.log('background.height(): ' + background.height());
            console.log('birdY: ' + birdY);
            console.log('thisTpipe.height(): ' + thisTpipe.height());
            console.log('thisBpipe.height(): ' + thisBpipe.height()); */
            // 当小鸟的高度不正确时
            if (birdY <= thisTpipe.height() || birdY + birdH >= background.height() - thisBpipe.height()) {
                /* console.log('birdH: ' + birdH);
                console.log('background.height(): ' + background.height());
                console.log('birdY: ' + birdY);
                console.log('thisTpipe.height(): ' + thisTpipe.height());
                console.log('thisBpipe.height(): ' + thisBpipe.height()); */
                console.log('撞到啦！！！！');
                gameover();
            } else {
                flag = true;
            }
        } else {
            // 离开管道时通过管道数量增加
            if (flag == true) {
                pipeNum += 1;
                flag = false;
            }
        }

        // 碰到天地
        // 页面高度减去小鸟高度
        birdHeight = parseInt(background.css('height')) - parseInt(bird.css('height'));

        // 天
        if (parseInt(birdicon.y) >= birdHeight) {
            bird.css('top', birdHeight);
            gameover();
        } else if (parseInt(birdicon.y) <= 0) {
            // 地
            bird.css('top', '0');
            gameover();
        }

        // 游戏结束
        function gameover() {
            $('.restart').show();
            $('.set').show();
            clearInterval(gofunc);
        }
        /* 速度！！！！！！3030303030 */
    }, speedMap.get(speed.val()));
}

// 背景点击事件
background.click(function () {
    /* 鼠标点击上升距离！！！！！！55555555 */
    birdicon.speedY = -(jump.val() * 2);
})

// 创建管道的函数
function createPipe(space, num) {
    var newpipe = $('<div class="pipeBox"><div class="tpipe"></div><div class="bpipe"></div></div>');
    background.append(newpipe);
    var tpipe = $('.tpipe');
    var bpipe = $('.bpipe');
    tpipe.eq(num).css({
        'position': 'absolute',
        'left': space + 'px',
        'top': '0',
        'height': getRandom(),
        'width': '52px',
        'background': 'url(https://s3.ax1x.com/2021/01/24/sbiXJP.png) center bottom no-repeat',
    })
    bpipe.eq(num).css({
        'position': 'absolute',
        'left': space + 'px',
        'bottom': '0',
        'height': getRandom(),
        'width': '52px',
        'background': 'url(https://s3.ax1x.com/2021/01/24/sbivz8.png) center top no-repeat',
    })
}

// 获取随机数(管道的随机长度)
function getRandom() {
    /* 管道垂直间距！！！！！180180180180 */
    ranHeight = Math.floor(Math.random() * 100 + (200 - vert.val() * 10));
    return ranHeight;
}